//
// Created by wujehy on 2020/5/16.
//

#include "EventManager.h"
#include "IoTBusiness.h"
#include "AuthBusiness.h"
#include "GeeJoan/NetWorkPackage.pb.h"

using namespace GeeJoan::Protocol::NetWork;

EventManager::EventManager()
{
    info( "init EventManager" );

    IoTBusiness *ioTBusiness = new IoTBusiness;
    AuthBusiness *authBusiness = new AuthBusiness;

    ioTBusiness->setEvents();
    authBusiness->setEvents();

    modMap.insert( std::pair<int, BaseBusiness *>( NetWorkPackageModel::IOTMod, ioTBusiness ));
    modMap.insert( std::pair<int, BaseBusiness *>( NetWorkPackageModel::AuthMod, authBusiness ));
}

EventManager::~EventManager()
{
    info( "delete EventManager" );

    for (auto mod : this->modMap)
    {
        if (mod.first == NetWorkPackageModel::AuthMod)
        {
            AuthBusiness *authBusiness = (AuthBusiness *) mod.second;
            delete authBusiness;
        } else if (mod.first == NetWorkPackageModel::IOTMod)
        {
            IoTBusiness *ioTBusiness = (IoTBusiness *) mod.second;
            delete ioTBusiness;
        }
        this->modMap.erase( mod.first );
    }

    info( "delete EventManager success" );

}

int EventManager::dispatchMod(
        int mod_type, int type_sub, int taskid, const TcpConnPtr &con, uint8_t *protoData, int datalen, void *userdata)
{
    auto mod = this->modMap.find( mod_type );
    int ret = -1;

    if (mod != this->modMap.end())
    {
        if (mod->first == NetWorkPackageModel::IOTMod)
        {
            IoTBusiness *iotmod = (IoTBusiness *) mod->second;
            ret = iotmod->dispatchEvents( type_sub, taskid, con, protoData, datalen, userdata );
        } else if (mod->first == NetWorkPackageModel::AuthMod)
        {
            AuthBusiness *authmod = (AuthBusiness *) mod->second;
            ret = authmod->dispatchEvents( type_sub, taskid, con, protoData, datalen, userdata );

        }
    } else
    {
        info( "not found Mod" );
        ret = -1;
    }

    return ret;
}
